package com.rgs.base.tasks.excel;

import com.google.common.io.Files;
import com.rgs.base.core.file.storage.FileStorageService;
import com.rgs.base.core.statics.CommonParamStaticClass;
import com.rgs.base.core.util.FileNameUtil;
import com.rgs.base.core.util.excel.AbstractAnalysisExcelListener;
import com.rgs.base.core.util.excel.ExcelUtil;
import com.rgs.base.tasks.task.AsyncTaskHandle;
import com.rgs.base.tasks.task.AsyncTaskRunnableBO;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.InputStream;
import java.time.LocalDate;

/**
 * @author Ren Gaoshuai
 * @date 2022-03-08 15:45
 **/
@Slf4j
public abstract class AbstractImportExcelHandle<D, T>
        implements AsyncTaskHandle {

    protected abstract FileStorageService getFileStorageService();

    protected abstract Class<T> getExcelClass();

    protected abstract AbstractAnalysisExcelListener<D, T> initAnalysisExcelListener
            (File errFileTemp, AsyncTaskRunnableBO asyncTaskRunnable);


    @Override
    public AsyncTaskRunnableBO execute(AsyncTaskRunnableBO asyncTaskRunnable) throws Exception {
        around(asyncTaskRunnable);
        return asyncTaskRunnable;
    }

    /**
     * 模板方法
     *
     * @param asyncTaskRunnable
     * @return com.wxhj.common.core.task.AsyncTaskRunnableBO
     * @author daxiong
     * @date 2020/8/13 11:45 上午
     */
    public AsyncTaskRunnableBO around(AsyncTaskRunnableBO asyncTaskRunnable)
            throws Exception {
        InputStream fileInputStream =
                this.getFileStorageService().obtainFileForInputStream(asyncTaskRunnable.getFileName());
        String fileUuid = FileNameUtil.generateNameFile(CommonParamStaticClass.OFFICE_EXCEL_XLSX);
        File tempDir = Files.createTempDir();
        File errFile = new File(tempDir, fileUuid);

        AbstractAnalysisExcelListener<D, T> analysisExcelListener =
                initAnalysisExcelListener(errFile,
                        asyncTaskRunnable);
        ExcelUtil.readExcel(fileInputStream,
                this.getExcelClass(), analysisExcelListener
        );
        //
//        this.getFileStorageService()
//                .saveFileInputStream(Files.asByteSource(errFile).openBufferedStream(),
//                        errFile.length(), fileUuid);
        this.getFileStorageService()
                .saveForInputStream(Files.asByteSource(errFile).openBufferedStream(), fileUuid);

        String fileName = asyncTaskRunnable.getTaskExplain() + "异常信息";
        asyncTaskRunnable.setStatus(analysisExcelListener.getAsyncTaskStatus().getCode());
        //需要优化
        asyncTaskRunnable.setFileName(fileUuid);
        asyncTaskRunnable.setFileUrl(this.getFileStorageService().fileUrl(fileUuid, fileName, LocalDate.now()));

        asyncTaskRunnable.setErrMassage("成功" + analysisExcelListener.getSuccessCount() + "个\n失败" + analysisExcelListener.getErrCount() + "个");
        return asyncTaskRunnable;
    }


}
